//
//  LBFixedPhotoView.m
//  app
//
//  Created by 杨庆人 on 16/12/20.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBFixedPhotoView.h"
#import <Masonry/Masonry.h>
#import <UICollectionViewLeftAlignedLayout/UICollectionViewLeftAlignedLayout.h>
#import "LBFixedPhotoCell.h"
#import <LBUIKit/LBPhotoBrowser.h>
#import <LBLoadingView/LBLoadingView.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>

static CGFloat const minimumLineSpacing = 10;
static CGFloat const minimumInteritemSpacing = 10;

@interface LBFixedPhotoView ()<UICollectionViewDataSource,UICollectionViewDelegate> {
    
    CGSize _itemSize;
    CGFloat _left;
    CGFloat _right;
}


@property (nonatomic,strong)UICollectionView * collectionView;
@property (nonatomic,strong)UICollectionViewLeftAlignedLayout * flowLayout;
@property (nonatomic,assign)LBServiceOSSCode OSSCode;
@property (nonatomic,strong)NSArray * imageNameArray;

@end
@implementation LBFixedPhotoView

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _flowLayout = [[UICollectionViewLeftAlignedLayout alloc] init];
        _flowLayout.sectionInset = UIEdgeInsetsMake(0, _left, 0, _right);
        _flowLayout.minimumLineSpacing = minimumLineSpacing;
        _flowLayout.minimumInteritemSpacing = minimumInteritemSpacing;
        _flowLayout.itemSize = _itemSize;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[LBFixedPhotoCell class] forCellWithReuseIdentifier:@"LBFixedPhotoCell"];
    }
    return _collectionView;
}
- (NSMutableArray <LBUploadPhotoModel *>*)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray <LBUploadPhotoModel *> alloc] init];
    }
    return _dataArray;
}

- (instancetype)initWithItemSize:(CGSize)itemSize left:(CGFloat)left right:(CGFloat)right imageNameArray:(NSArray *)imageNameArray OSSCode:(LBServiceOSSCode)OSSCode{
    if (self = [super init]) {
        _itemSize = itemSize;
        _left = left;
        _right = right;
        _OSSCode = OSSCode;
        _imageNameArray = imageNameArray;
        [self creatCollectionView];
    }
    return self;
}

- (instancetype)initWithImageNameArray:(NSArray *)imageNameArray OSSCode:(LBServiceOSSCode)OSSCode {

    return [self initWithItemSize:CGSizeMake(LBPicturesMargin, LBPicturesMargin) left:15 right:15 imageNameArray:imageNameArray OSSCode:OSSCode];
}

- (void)creatCollectionView {
    
    for (int i = 0 ; i < self.imageNameArray.count ;i ++) {
        LBUploadPhotoModel * model = [[LBUploadPhotoModel alloc] init];
        [self.dataArray addObject:model];
    }
    
    
    
    [self addSubview:self.collectionView];

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self);
        make.height.mas_equalTo(_itemSize.height);
        make.bottom.mas_equalTo(self.mas_bottom);
    }];
    
    [self updataViewHeight:self.dataArray];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LBFixedPhotoCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LBFixedPhotoCell" forIndexPath:indexPath];
    
    __weak typeof(self)weakSelf = self;
    [cell setCellWithUploadPhotoModel:self.dataArray[indexPath.row] itemName:self.imageNameArray[indexPath.row] indexPath:indexPath photoCellType:LBItemNameInBottom deleBlock:^(NSIndexPath *deIndexPath) {
        // 删除照片
        weakSelf.dataArray[deIndexPath.row] = [LBUploadPhotoModel new];
        [weakSelf updataViewHeight:weakSelf.dataArray];
        [weakSelf.collectionView reloadData];
    }];
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self)weakSelf = self;
    
    LBUploadPhotoModel * photoModel = self.dataArray[indexPath.row];
    
    if (photoModel.urlString.length || photoModel.objectKey.length || photoModel.image) {
        NSMutableArray * browserArray = [[NSMutableArray alloc] init];
        for (LBUploadPhotoModel * model in self.dataArray) {
            if (model.urlString.length) {
                [browserArray addObject:model.urlString];
            }
            else if (model.image) {
                [browserArray addObject:model.image];
            }
        }
        NSMutableArray *array = [NSMutableArray new];
        for (id obj in browserArray) {
            if ([obj isKindOfClass:[NSString class]]) {
                LBPhoto *photo = [[LBPhoto alloc]initWithURLString:obj];
                [array addObject:photo];
            }
            else if ([obj isKindOfClass:[UIImage class]]){
                LBPhoto *photo = [[LBPhoto alloc]initWithImage:obj];
                [array addObject:photo];
            }
            
            
        }
        LBFixedPhotoCell *cell = (LBFixedPhotoCell*)[collectionView cellForItemAtIndexPath:indexPath];
        [LBPhotoBrowser showWithPhotos:array selectIndex:indexPath.row sourceImageViewClosure:^UIImageView *(NSInteger index) {
            return cell.bgImageView;
        }];
    
    }
    else{
        LBUploadPhotoModel * model = [[LBUploadPhotoModel alloc] init];
        
        [LBActionSheet showImagePickerInView:self.superview completion:^(NSDictionary<NSString *,id> *info) {
            
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            
            UIImage * newImage = [LBActionSheet fixOrientation:image];
            
            while (newImage.size.width > 1500) {
                newImage = [self imageWithImageSimple:newImage scaledToSize:CGSizeMake(newImage.size.width * 0.5, newImage.size.height * 0.5)];
            }
            
   
            NSData *imgData = UIImageJPEGRepresentation(newImage, 1);
            
            // 5M
            while (imgData.length / (1024.0 * 1024) > 5) {
                imgData = UIImageJPEGRepresentation(newImage, 0.5);
                newImage = [UIImage imageWithData:imgData];
            }
            
            if (image !=nil) {
                //获取图片的名字
                __block NSString* imageFileName;
                NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
                ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) {
                    ALAssetRepresentation *representation = [myasset defaultRepresentation];
                    imageFileName = [representation filename];
                    model.imageFileName = imageFileName;
                };
                
                ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
                [assetslibrary assetForURL:imageURL
                               resultBlock:resultblock
                              failureBlock:nil];
            }
            
            [LBLoadingView showWithText:@"正在上传..."];
            
            [LBOSSService getOSSUploadDataWithFile:imgData fileType:weakSelf.OSSCode contentType:LBOSSContentTypePNG progressBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                
                
                
            } uploadSuccess:^(NSString *objectKey) {
                
                model.image = image;
                model.objectKey = objectKey;
                
            } getUrlSuccess:^(NSString *UrlString) {
                // 获取到图片的url

                model.urlString = UrlString;
                
                weakSelf.dataArray[indexPath.row] = model;
                
                [weakSelf updataViewHeight:weakSelf.dataArray];
                [weakSelf.collectionView reloadData];
                
                
                [LBLoadingView dismiss];
                
            } failure:^(NSError *error, NSString *message) {
                [LBLoadingView dismiss];
            }];
        }];
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (void)updataViewHeight:(NSMutableArray *)dataArray {
    
    self.viewHeight = [self heightForCollectionViewWithItemCount:_dataArray.count];
    
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.viewHeight);
    }];
}
- (void)setFixedPhotoViewWithImageUrlArray:(NSArray *)imageUrlArray {
    
    NSMutableArray * dataArray = [[NSMutableArray alloc] init];
    if (imageUrlArray.count) {
        if ([imageUrlArray.firstObject isKindOfClass:[LBUploadPhotoModel class]]) {
            dataArray = [NSMutableArray arrayWithArray:imageUrlArray];
        }
        else {
            for (id urlString in imageUrlArray) {
                LBUploadPhotoModel * model = [[LBUploadPhotoModel alloc] init];
                if ([urlString isKindOfClass:[UIImage class]]) {
                    model.image = urlString;
                }
                else {
                    model.urlString = urlString;
                }
                [dataArray addObject:model];
            }
        }
    }
    
    NSInteger differNum = self.dataArray.count - dataArray.count;
    self.dataArray = dataArray;
    if (differNum > 0) {
        for (int i = 0; i < differNum; i ++) {
            [self.dataArray addObject:[LBUploadPhotoModel new]];
        }
    }
    
    [self updataViewHeight:self.dataArray];
    [self.collectionView reloadData];
}
- (CGFloat)heightForCollectionViewWithItemCount:(NSInteger)itemCount
{
    NSInteger row = 1;
    
    CGFloat width = [[UIScreen mainScreen] bounds].size.width - _left - _right;
    
    NSInteger rowCount = (NSInteger)width / (_itemSize.width + minimumInteritemSpacing);
    
    if (rowCount * (_itemSize.width + minimumInteritemSpacing) + _itemSize.width <= width) {
        rowCount ++;
    }
    if (itemCount > rowCount) {
        NSInteger addRow = itemCount / rowCount;
        row += addRow;
        if (itemCount % rowCount == 0) {
            row -= 1;
        }
    }
    return row * _itemSize.height + (row - 1) * minimumLineSpacing;
}

- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
@end

